"use strict";

import { app, protocol, BrowserWindow, Menu, IpcMainEvent, ipcMain } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import { MenuItemConstructorOptions } from "electron/main";
const isDevelopment = process.env.NODE_ENV !== "production";

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

let win: BrowserWindow;

// 设置菜单栏
function createMenu() {
  // let array = new Array<String>('', '2' , '3');
  // darwin表示macOS，针对macOS的设置
  if (process.platform === "darwin") {
    const template = new Array<MenuItemConstructorOptions>({
      label: "App Demo",
      submenu: [
        {
          role: "about",
        },
        {
          role: "quit",
        },
      ],
    });
    let menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
  } else {
    // windows及linux系统
    Menu.setApplicationMenu(null);
  }
}

async function createWindow() {
  // Create the browser window.
  win = new BrowserWindow({
    width: 1200,
    height: 700,
    minWidth: 700,
    minHeight: 500,
    frame: false,
    webPreferences: {
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      nodeIntegration: (process.env.ELECTRON_NODE_INTEGRATION as unknown) as boolean,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    win.loadURL("app://./index.html");
  }
  createMenu();
}

// Quit when all windows are closed.
app.on("window-all-closed", () => {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on("ready", async () => {
  // if (isDevelopment && !process.env.IS_TEST) {
  //   // Install Vue Devtools
  //   try {
  //     await installExtension(VUEJS3_DEVTOOLS)
  //   } catch (e) {
  //     console.error('Vue Devtools failed to install:', e.toString())
  //   }
  // }
  createWindow();

  win.on("close", (event) => {
    console.log("window closed");
  });

  // 监听窗口最大化
  win.on("maximize", () => {
    console.log("window maximized");
    win.webContents.send('maximize')
  });

  // 监听窗口最大化还原
  win.on("unmaximize", () => {
    console.log("window unmaximize");
    win.webContents.send('unmaximize')
  });

  // 监听窗口大小变化
  win.on("resized", () => {
    console.log("window resize");
    win.webContents.send("windowResize", win.getContentSize());
  });

  // 事件必须有返回值，否则会出现异常
  ipcMain.on("maximize", (event: IpcMainEvent, arg) => {
    win.maximize();
    event.returnValue = true;
  });

  ipcMain.on("unmaximize", (event: IpcMainEvent, arg) => {
    win.unmaximize();
    event.returnValue = true;
  });

  ipcMain.on("minimize", (event: IpcMainEvent, arg) => {
    win.minimize();
    event.returnValue = true;
  });

  // 在打开dev tools时无法关闭窗口，虽然会调用方法
  ipcMain.on("close", (event: IpcMainEvent, arg) => {
    win.close();
    console.log("ipcMain close");
    event.returnValue = true;
  });

  ipcMain.on("quit", (event: IpcMainEvent, arg) => {
    app.quit();
    event.returnValue = true;
  });

  // 异步
  ipcMain.on("asynchronous-message", (event: IpcMainEvent, arg) => {
    event.reply("asynchronous-reply", "pong");
  });

  // 同步
  ipcMain.on("synchronous-message", (event: IpcMainEvent, arg) => {
    event.returnValue = "pong";
  });

  ipcMain.on("getPath", (event: IpcMainEvent, arg) => {
    try {
      event.returnValue = app.getPath(arg);
    } catch (error) {
      event.returnValue = null;
    }
  });

  // 获取窗口大小
  ipcMain.on("getContentSize", (event, arg) => {
    event.returnValue = win.getContentSize();
  });
});

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
  if (process.platform === "win32") {
    process.on("message", (data) => {
      if (data === "graceful-exit") {
        app.quit();
      }
    });
  } else {
    process.on("SIGTERM", () => {
      app.quit();
    });
  }
}
